
package com.ueffort.social;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import com.ueffort.social.action.AuthAction;
import com.ueffort.social.action.RealAction;
import com.ueffort.social.action.ShareAction;
import com.ueffort.social.action.LeaderboardAction;
import com.ueffort.social.action.AchievementAction;
import com.ueffort.social.action.SocialAction;
import com.ueffort.social.inter.ShareObject;
import com.unity3d.player.*;

public class SocialSDK implements SocialAction {
    private static SocialSDK instance=new SocialSDK();

    static Activity mActivity;

    public enum SocialPlatformType{
        Token,
        GameCenter,
        Wechat,
        Facebook,
        GooglePlay,
        Mi,
        Huawei,
        Uc,
        TapCn,
        TapIo,
        Steam,
    }
    private static SocialPlatformType[] platformList = {
            SocialPlatformType.Token,
            SocialPlatformType.GameCenter,
            SocialPlatformType.Wechat,
            SocialPlatformType.Facebook,
            SocialPlatformType.GooglePlay,
            SocialPlatformType.Mi,
            SocialPlatformType.Huawei,
            SocialPlatformType.Uc,
            SocialPlatformType.TapCn,
            SocialPlatformType.TapIo,
            SocialPlatformType.Steam,
    };
    private static Dictionary<SocialPlatformType, String> platformClassDefine = new Hashtable<SocialPlatformType, String>();
    private static Dictionary<SocialPlatformType, SocialProvider> mPlatformList=new Hashtable<>();
    private static SocialCallbackListener callbackListener;
    static {
        {
            platformClassDefine.put(SocialPlatformType.Wechat, "com.ueffort.social.platform.WechatSocialProvider");
            platformClassDefine.put(SocialPlatformType.Facebook, "com.ueffort.social.platform.FacebookSocialProvider");
            platformClassDefine.put(SocialPlatformType.GooglePlay, "com.ueffort.social.platform.GoogleSocialProvider");
            platformClassDefine.put(SocialPlatformType.Mi, "com.ueffort.social.platform.MiSocialProvider");
            platformClassDefine.put(SocialPlatformType.Huawei, "com.ueffort.social.platform.HuaweiSocialProvider");
            platformClassDefine.put(SocialPlatformType.Uc, "com.ueffort.social.platform.UcSocialProvider");
            platformClassDefine.put(SocialPlatformType.TapCn, "com.ueffort.social.platform.TapcnSocialProvider");
            platformClassDefine.put(SocialPlatformType.TapIo, "com.ueffort.social.platform.TapTapSocialProvider");
        }
        mActivity = UnityPlayer.currentActivity;
        Enumeration<SocialPlatformType> a = platformClassDefine.keys();
        while(a.hasMoreElements()){
            SocialPlatformType p = a.nextElement();
            try {
                Class cls = Class.forName(platformClassDefine.get(p));
                if(null != cls){
                    mPlatformList.put(p, (SocialProvider) cls.getMethod("Instance").invoke(null));
                }

            } catch (ClassNotFoundException | NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        checkActivity();
    }

    public static void onActivityResult(int requestCode, int resultCode, Intent data){
        Enumeration<SocialProvider> e = mPlatformList.elements();
        while(e.hasMoreElements()){
            SocialProvider provider = e.nextElement();
            if (provider.onActivityResult(requestCode, resultCode, data)) {
                break;
            }
        }
    }

    private static int getPlatform(SocialPlatformType platformType){
        for (int i = 0; i < platformList.length; i++) {
            if (platformType == platformList[i]) {
                return i;
            }
        }
        return -1;
    }
    private static SocialPlatformType getPlatform(int location) {
        int length = platformList.length;
        return location >= 0 && location < length?platformList[location]:null;
    }

    public static void onCreate(Activity activity){
        Enumeration<SocialProvider> e = mPlatformList.elements();
        while(e.hasMoreElements()){
            SocialProvider provider = e.nextElement();
            provider.onCreate(activity);
        }
    }

    public static void onDestroy(Activity activity){
        Enumeration<SocialProvider> e = mPlatformList.elements();
        while(e.hasMoreElements()){
            SocialProvider provider = e.nextElement();
            provider.onDestroy(activity);
        }
    }

    public static void bindCallback(SocialCallbackListener listener){
        callbackListener = listener;
    }

    @Override
    public void OnLogout(SocialPlatformType platform) {
        if(callbackListener!=null) callbackListener.OnLogout(getPlatform(platform));
    }

    public static void register(int platform, String appId, final SocialRegisterListener listener){
        checkActivity();
        Log.e("social", "register: "+getPlatform(platform));
        if (getPlatform(platform)==null){
            runInUI(new Runnable() {
                @Override
                public void run() {
                    listener.onRegister(platform, false, false, false, false, false);
                }
            });
            return;
        }

        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        Log.e("social", "register: "+provider);
        if (provider==null){
            runInUI(new Runnable() {
                @Override
                public void run() {
                    listener.onRegister(platform, false, false, false, false, false);
                }
            });
            return;
        }
        try{
            provider.Init(appId, UnityPlayer.currentActivity, instance);
            runInUI(new Runnable() {
                @Override
                public void run() {
                    listener.onRegister(platform, provider.isInstall(), provider.isShared(), provider.isLeaderboard(), provider.isAchievement(), provider.isReal());
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void logout(int platform, final LogoutListener listener){
        checkActivity();
        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        provider.Logout();
        listener.onLogout(platform);
    }

    public static void authorize(int platform, final AuthListener listener) {
        checkActivity();
        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        provider.Authorize(new AuthAction() {
            @Override
            public void onError(final SocialPlatformType arg0, final Throwable arg2) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onAuth(getPlatform(arg0), 0,"error",arg2.getMessage());
                    }
                });
            }

            @Override
            public void onComplete(final SocialPlatformType arg0, final Map<String, String> arg2) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        String keys = "";
                        String values = "" ;
                        int i = 0;
                        for (String key :arg2.keySet()) {
                            i++;

                            keys = keys+key;
                            if (i<=(arg2.keySet().size()-1)) {
                                keys=keys+",";
                            }
                        }
                        int j = 0;
                        for (String value :arg2.values()) {
                            j++;
                            if (value == null){
                                value = "null";
                            }else if (value.contains(",")){
                                value = value.replace(","," ");
                            }
                            values = values+value;
                            if (j<=(arg2.values().size()-1)) {
                                values=values+",";
                            }
                        }

                        Log.e("social"," keys="+keys+", values="+values);
                        listener.onAuth(getPlatform(arg0), 200, keys,values);
                    }
                });
            }

            @Override
            public void onCancel(final SocialPlatformType arg0) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onAuth(getPlatform(arg0), -1,"error","cancel");
                    }
                });
            }
        });
    }

    public static void isAuthorized(int platform, final AuthListener listener) {
        checkActivity();
        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        provider.AuthorizeStatus(new AuthAction() {
            @Override
            public void onError(final SocialPlatformType arg0, final Throwable arg2) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onAuth(getPlatform(arg0), 0,"error",arg2.getMessage());
                    }
                });
            }

            @Override
            public void onComplete(final SocialPlatformType arg0, final Map<String, String> arg2) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        String keys = "";
                        String values = "" ;
                        int i = 0;
                        for (String key :arg2.keySet()) {
                            i++;

                            keys = keys+key;
                            if (i<=(arg2.keySet().size()-1)) {
                                keys=keys+",";
                            }
                        }
                        int j = 0;
                        for (String value :arg2.values()) {
                            j++;
                            if (value == null){
                                value = "null";
                            }else if (value.contains(",")){
                                value = value.replace(","," ");
                            }
                            values = values+value;
                            if (j<=(arg2.values().size()-1)) {
                                values=values+",";
                            }
                        }

                        Log.e("social"," keys="+keys+", values="+values);
                        listener.onAuth(getPlatform(arg0), 200, keys,values);
                    }
                });
            }

            @Override
            public void onCancel(final SocialPlatformType arg0) {
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onAuth(getPlatform(arg0), -1,"error","unauth");
                    }
                });
            }
        });
    }

    public static void real(int platform, RealListener listener){
        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        provider.Real(new RealAction() {
            @Override
            public void onResult(SocialPlatformType arg0) {
                listener.onReal(getPlatform(arg0), 200, "success");
            }

            @Override
            public void onError(SocialPlatformType arg0, Throwable arg1) {
                listener.onReal(getPlatform(arg0), -1, arg1.getMessage());
            }

            @Override
            public void onCancel(SocialPlatformType arg0) {
                listener.onReal(getPlatform(arg0), 0, "cancel");
            }
        });
    }

    public static void directShare(int platform, String title, String imagePath, String description, String webUrl, String videoUrl, final ShareListener listener) {
        checkActivity();

        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        ShareObject share = new ShareObject();
        share.title = title;
        share.description = description;
        share.webUrl = webUrl;
        share.thumb = imagePath;
        share.videoUrl = videoUrl;

        provider.ShareWithObject(share, new ShareAction() {

            @Override
            public void onResult(SocialPlatformType arg0) {
                Log.e("social","success");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onShare(getPlatform(arg0), 200, "success");
                    }
                });
            }

            @Override
            public void onError(SocialPlatformType arg0, Throwable arg1) {
                UnityPlayer.UnitySendMessage("social", "onShareback", "error"+arg1.getMessage());
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onShare(getPlatform(arg0), -1, arg1.getMessage());
                    }
                });
            }

            @Override
            public void onCancel(SocialPlatformType arg0) {
                UnityPlayer.UnitySendMessage("social", "onShareback", "cancel");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onShare(getPlatform(arg0), 0, "cancel");
                    }
                });
            }
        });
    }

    public static void updateData(int platform, String key, String value){
        SocialProvider provider = mPlatformList.get(getPlatform(platform));
        String[] keys = key.split(",");
        String[] values = value.split(",");
        Map<String, String> dic = new HashMap<String, String>();
        //dic.Add (keys , values );
        for (int i = 0; i < keys.length; i++)
        {
            dic.put(keys[i], values[i]);
        }
        provider.UpdateData(dic);
    }

    public static void submitLeaderboard(int platform, String key, int value, final LeaderboardListener listener) {
        checkActivity();

        SocialProvider provider = mPlatformList.get(getPlatform(platform));

        provider.SubmitLeaderboard(key ,value, new LeaderboardAction() {

            @Override
            public void onResult(SocialPlatformType arg0) {
                Log.e("social","success");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onLeaderboard(getPlatform(arg0), 200, "success");
                    }
                });
            }

            @Override
            public void onError(SocialPlatformType arg0, Throwable arg1) {
                UnityPlayer.UnitySendMessage("social", "onLeaderboard", "error"+arg1.getMessage());
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onLeaderboard(getPlatform(arg0), -1, arg1.getMessage());
                    }
                });
            }

            @Override
            public void onCancel(SocialPlatformType arg0) {
                UnityPlayer.UnitySendMessage("social", "onLeaderboard", "cancel");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onLeaderboard(getPlatform(arg0), 0, "cancel");
                    }
                });
            }
        });
    }

    public static void addAchievement(int platform, String key, int value, final AchievementListener listener) {
        SocialProvider provider = mPlatformList.get(getPlatform(platform));

        provider.AddAchievement(key ,value, new AchievementAction() {

            @Override
            public void onResult(SocialPlatformType arg0) {
                Log.e("social","success");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onAchievement(getPlatform(arg0), 200, "success");
                    }
                });
            }

            @Override
            public void onError(SocialPlatformType arg0, Throwable arg1) {
                UnityPlayer.UnitySendMessage("social", "onAchievement", "error"+arg1.getMessage());
                runInUI(new Runnable() {
                    @Override
                    public void run() {
                        listener.onAchievement(getPlatform(arg0), -1, arg1.getMessage());
                    }
                });
            }

            @Override
            public void onCancel(SocialPlatformType arg0) {
                UnityPlayer.UnitySendMessage("social", "onAchievement", "cancel");

                runInUI(new Runnable() {

                    @Override
                    public void run() {
                        listener.onAchievement(getPlatform(arg0), 0, "cancel");
                    }
                });
            }
        });
    }

    private static void runInUI(Runnable runnable) {
        UnityPlayer.currentActivity.runOnUiThread(runnable);
    }
    private static String getFileName(String fullname) {
        return !fullname.startsWith("assets/") && !fullname.startsWith("res/")?"":fullname.split("/")[1];
    }

    private static void parseShareImage(String imgName) {
        if(TextUtils.isEmpty(imgName)) {

            return ;
        } else {
            if(imgName.startsWith("http")) {
            } else if(imgName.startsWith("assets/")) {
                AssetManager imgFile = UnityPlayer.currentActivity.getResources().getAssets();
                String index = getFileName(imgName);
                InputStream imgNameString = null;
                if(!TextUtils.isEmpty(index)) {
                    try {
                        imgNameString = imgFile.open(index);
                        imgNameString.close();
                    } catch (IOException var14) {
                        var14.printStackTrace();
                    } finally {
                        if(imgNameString != null) {
                            try {
                                imgNameString.close();
                            } catch (IOException var13) {
                                var13.printStackTrace();
                            }
                        }

                    }
                }
            } else if(imgName.startsWith("res/")) {
                String imgFile1 = getFileName(imgName);
                if(!TextUtils.isEmpty(imgFile1)) {
                    int index1 = imgFile1.indexOf(".");
                    if(index1 > 0) {
                        String imgNameString1 = imgFile1.substring(0, index1);
                    } else {
                        Log.e("social", "### 请检查你传递的图片路径 : " + imgName);
                    }
                }
            } else {
                File imgFile2 = new File(imgName);
                if(!imgFile2.exists()) {
                    Log.e("social", "### 要分享的本地图片不存在");
                }
            }

        }
    }

    public static void updateOwnerActivity(Activity activity) {
        mActivity = activity;
    }

    private static void checkActivity() {
        assert UnityPlayer.currentActivity != null : "在SocialSDK类中, mActivity为null.";
    }

}
